package com.lc.controller;

import com.lc.constant.Constants;
import com.lc.pojo.UmsUser;
import com.lc.pojo.dto.UmsUserDto;
import com.lc.result.Result;
import com.lc.result.ResultEnum;
import com.lc.result.ResultUtils;
import com.lc.service.UmsUserService;
import com.lc.utils.JWTUtil;
import com.lc.utils.SmsUtil;
import com.lc.utils.ThreadVariablesUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 登录
 */

@RestController
@RequestMapping("/ums/user")
public class UmsUserController {

    @Resource
    private UmsUserService umsUserService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 登录获取token
     * @param phone 手机号
     * @param sms 短信验证码
     * @return
     */
    @PostMapping("/login")
    public Result login(String phone, String sms){

        //非空验证
        if (!SmsUtil.isEmpty(phone)) {
            return ResultUtils.returnResult(ResultEnum.FAIL_UMS_PHONE_ERROR);
        }
        //格式验证
        if (!SmsUtil.matchReg(phone)) {
            return ResultUtils.returnResult(ResultEnum.FAIL_UMS_PHONE_ERROR);
        }
        //校验两次号码是否相同
        String sendCode = (String)redisTemplate.opsForValue().get(Constants.Redis.PREFIX_SMS + phone);
        if (sendCode == null || !sms.equals(sendCode)) {
            ResultUtils.returnResult(ResultEnum.FAIL_UMS_SMS_CODE_ERROR);
        }

        //生成token
        UmsUser umsUser = umsUserService.getUserToken(phone);
        String token = JWTUtil.createToken(umsUser);
        //将token存入redis，设置过期时间为30分钟
        System.out.println(redisTemplate);
        redisTemplate.opsForValue().set(Constants.Redis.PREFIX_TOKEN,token,30, TimeUnit.MINUTES);

        HashMap<String, Object> map = new HashMap<>();
        map.put(Constants.Redis.PREFIX_TOKEN, token);

        return ResultUtils.returnDataSuccess(map);

    }

    /**
     * 解析token，获取用户信息
     * @return
     */
    @GetMapping("/getUserByToken")
    public Result getUserByToken(){
        UmsUser umsUser = ThreadVariablesUtil.getThreadData();

        UmsUserDto umsUserDto = new UmsUserDto();
        BeanUtils.copyProperties(umsUser,umsUserDto);

        return ResultUtils.returnDataSuccess(umsUserDto);
    }

    /**
     * 退出登录
     * @return
     */
    @GetMapping("/logout")
    public Result logout(){
        // 清空本地线程中的用户信息
        ThreadVariablesUtil.removeThreadData();

        // 删除token
        Boolean delete = redisTemplate.delete(Constants.Redis.PREFIX_TOKEN);
        if(!delete){
            return ResultUtils.returnFail();
        }
        return ResultUtils.returnSuccess();
    }

}
